<?php

namespace App\Http\Controllers\Api;

use App\Handlers\ImageUploadHandler;
use App\Http\Requests\Api\UserAddrRequest;
use App\Http\Requests\Api\UserInfoRequest;
use App\Models\DealLog;
use App\Models\DealLine;
use App\Models\EDealLog;
use App\Models\Member;
use App\Models\PowerLog;
use App\Models\PowerType;
use App\Models\Recharge;
use App\Models\Shop;
use App\Models\ShopProfit;
use App\Models\ShopRole;
use App\Models\User;
use App\Models\UserAddr;
use App\Models\Wallet;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use QrCode;

/**
 * @title 个人中心
 * @description 接口说明
 * @header name:accessToken require:1 default: desc:accessToken
 */

class UserController extends ApiController
{
    public function __construct()
    {
        $this->offset = 10;
    }

    public function userInfo(Request $request)
    {
        return $this->success(UserTransformer::transform($request->user));
    }
    /**
     * @title 修改头像
     * @description 接口说明
     * @author wjx
     * @url /api/user/update_avatar
     * @method POST
     *
     * @param name:avatar type:string require:1 default:1 other: desc:用户头像(base64)
     *
     * @return avatar:新头像地址
     */
    public function update_avatar(Request $request, ImageUploadHandler $uploader)
    {
        $this->validate(
            request(),
            [
                // 'avatar' => 'required|mimes:jpeg,bmp,png,gif|dimensions:min_width=200,min_height=200',
                'avatar' => 'required',
            ],
            [
                'avatar.required' => '请选择图片',
                // 'avatar.mimes' => '图片格式错误，请重新选择',
                // 'avatar.dimensions' => '图片的清晰度不够，宽和高需要 200px 以上',
            ]
        );
        $user = $request->user;

        $result = $uploader->saveBase64Image($request->avatar, 'avatars', $user->id);
        if ($result) {
            if (!$user->avatar) {
                Wallet::update_power($user->id, 10, 1);
                PowerLog::add_log($user->id, 4, 10, 1);
            }
            $user->avatar = $result['path'];
            $user->regType = 0;
        } else {
            return $this->failed('头像修改失败');
        }
        $res = $user->save();
        // $avatar = config('app.img_url') . $user->avatar;
        $avatar = $user->avatar;
        if ($res) {
            return $this->success(compact('avatar'));
        } else {
            return $this->failed('头像修改失败');
        }
    }

    /**
     * @title 修改昵称
     * @description 接口说明
     * @author wjx
     * @url /api/user/update_nickname
     * @method POST
     * @module 新手任务
     *
     *
     * @param name:nickname type:string require:1 default:1 other: desc:昵称
     */
    public function update_nickname(Request $request)
    {
        $user = $request->user;
        $this->validate(
            request(),
            [
                'nickname' => 'required|between:3,25|unique:users,nickname,' . $user->id,
            ],
            [
                'nickname.required' => '用户名不能为空。',
                'nickname.between' => '用户名必须介于 3 - 25 个字符之间。',
                'nickname.unique' => '用户名已被占用，请重新填写。',
            ]
        );
        if (!$user->nickname) {
            Wallet::update_power($user->id, 10, 1);
            PowerLog::add_log($user->id, 4, 10, 1);
        }
        $user->nickname = $request->nickname;
        $user->save();
        return $this->message('昵称修改成功');

    }

    /**
     * @title 修改个性签名
     * @description 接口说明
     * @author wjx
     * @url /api/user/updatePersonalSignature
     * @method POST
     * @module 新手任务
     *
     *
     * @param name:personal_signature type:string require:1 default: other: desc:个性签名
     *
     */
    public function updatePersonalSignature(Request $request): object
    {
        $user = $request->user;
        $this->validate(
            request(), [
                'personal_signature' => 'between:1,30',
            ],
            [
                'personal_signature.between' => '个性签名必须介于 1 - 30 个字符之间',
            ]
        );
        if (!$user->personal_signature) {
            Wallet::update_power($user->id, 10, 1);
            PowerLog::add_log($user->id, 4, 10, 1);
        }
        $user->personal_signature = $request->personal_signature;
        $user->save();
        return $this->message('个性签名修改成功');
    }
    /**
     * @title 实名认证
     * @description 接口说明
     * @author wjx
     * @url /api/user/set_real
     * @method POST
     * @module 新手任务
     *
     *
     * @param name:real_name type:string require:1 default: other: desc:真实姓名
     * @param name:id_card type:string require:1 default: other: desc:身份证号
     *
     */
    public function set_real(Request $request)
    {
        $user = $request->user;
        if (!$request->real_name || !$request->id_card) {
            return $this->failed('缺少参数');
        }
        DB::beginTransaction();
        try {
            if (!$user->real_name) {
                Wallet::update_power($user->id, 10, 1);
                PowerLog::add_log($user->id, 4, 10, 1);
            }
            $user->real_name = $request->real_name;
            $user->id_card = $request->id_card;
            $user->save();
            DB::commit();
            return $this->message('修改成功');
        } catch (\Exception $exception) {

            DB::rollBack();
            return $this->failed('修改失败');
        }

    }
    /**
     * @title 邀请好友页面
     * @description 接口说明
     * @author wjx
     * @url /api/user/invite_share
     * @method POST
     *
     * @return url:邀请地址
     * @return qrcode:二维码（base64）
     * @return s_avatar:头像列表
     */
    public function invite_share(Request $request)
    {
        $user = $request->user;
        $data = [];
        $data['url'] = config('app.url') . '/register/' . $user->code;
        $data['qrcode'] = base64_encode(QrCode::format('png')->size(100)->generate($data['url']));

        $s_users = User::where('pid', $user->id)->get()->pluck('avatar');
        
        $data['s_avatar'] = $s_users;
        return $this->success($data);

    }
    /**
     * @title 填写邀请码
     * @description 接口说明
     * @author wjx
     * @url /api/user/invite_code
     * @method POST
     *
     * @param name:invite_code type:string require:1 default: other: desc:邀请码
     *
     */
    public function invite_code(Request $request)
    {
        $invite_code = $request->invite_code;
        $user = $request->user;
        if (!$invite_code) {
            return $this->failed('请填写邀请码');
        }
        if ($user->pid !== 0) {
            return $this->failed('你已经填写过邀请码，不能重复填写');
        }
        $p_user = $user->where('code', $invite_code)->first();
        if (!$p_user) {
            return $this->failed('邀请人不存在或邀请码错误');
        }
        DB::beginTransaction();
        try {
            $user->update(['pid' => $p_user->id]);
            Wallet::update_power($p_user->id, 10, 1);
            PowerLog::add_log($p_user->id, 5, 10, 1);
            DB::commit();
            return $this->message('修改成功');
        } catch (\Exception $exception) {

            DB::rollBack();
            return $this->failed('修改失败');
        }
    }

    /**
     * @title 我的
     * @description 接口说明
     * @author wjx
     * @url /api/user/my
     * @method POST
     *
     * @return nickname:别名
     * @return avatar:头像
     * @return phone:手机号
     * @return tmc:虚拟货币资产
     * @return is_member:是否为会员
     * @return member_start_time:会员开始时间
     * @return member_end_time:会员结束时间
     * @return weixin_withdraw_nickname:微信提现昵称
     * @return is_bind:是否绑定微信1是0否
     * @return is_real:是否实名认证1是0否
     * @return code:我的邀请码
     * @return personal_signature:个性签名
     * @return is_dep:是否交过押金1是0否
     * @return today_price:今日e格码价格
     * @return msg_count:未读消息数量
     * @return robe_num:最多借衣数量
     * 
     *
     */
    public function my(Request $request, Member $member, User $user)
    {
        $user = $request->user;
        $data = [];
        $member = $user->member;
        $data['nickname'] = $user->nickname;
        $data['avatar'] = $user->avatar;
        $data['phone'] = $user->phone;
        $data['tmc'] = $user->wallet->tmc;
        $data['is_member'] = $user->is_member;
        $data['level'] = $user->level;
        $data['weixin_withdraw_nickname'] = $user->weixin_withdraw_nickname;
        $data['real_name'] = $user->real_name;
        $data['code'] = $user->code;
        $data['personal_signature'] = $user->personal_signature;
        $data['hasPhone'] = $user->hasPhone;
        $data['hasPwd'] = $user->hasPwd;
        $data['hasPayPwd'] = $user->hasPayPwd;
        $data['regType'] = $user->regType;
        $data['member_start_time'] = ($user->member_start_time) ? date('Y-m-d', $user->member_start_time) : '';
        $data['member_end_time'] = ($user->member_end_time) ? date('Y-m-d', $user->member_end_time) : '';
        if ($user->weixin_withdraw_openid) {
            $data['is_bind'] = 1;
        } else {
            $data['is_bind'] = 0;
        }
        if ($user->real_name) {
            $data['is_real'] = 1;
        } else {
            $data['is_real'] = 0;
        }

        if ($user->wallet->deposit > 0) {
            $data['is_dep'] = 1;
        } else {
            $data['is_dep'] = 0;
        }
        $today_price = DealLine::orderBy('id', 'desc')->value('price');
        $data['today_price'] = $today_price;
        $data['msg_count'] = $user->notifications()->whereNull('read_at')->count();
        $data['robe_num'] = $user->robe_num;

        return $this->success($data);

    }
    public function update_info(Request $request, UserInfoRequest $userinfo, ImageUploadHandler $uploader)
    {
        $user = $request->user;
        $result = $uploader->saveBase64Image($userinfo->avatar, 'avatars', $user->id);
        if ($result) {
            $user->avatar = $result['path'];
        } else {
            return $this->failed('头像修改失败');
        }

        $user->nickname = $userinfo->nickname;
        $user->personal_signature = $userinfo->personal_signature;
        $res = $user->save();
        if ($res) {
            return $this->message('修改成功');
        } else {
            return $this->failed('系统错误');
        }
    }
    /**
     * @title 我的收益
     * @description 接口说明
     * @author wjx
     * @url /api/user/my_profit
     * @method POST
     *
     * @return computing_power:算力
     * @return tmc:E格码
     * @return money:余额
     *
     */
    public function my_profit(Request $request)
    {
        $user = $request->user;
        $wallet = $user->wallet;
        $detail = $wallet->only(['computing_power', 'tmc', 'money']);
        
        return $this->success($detail);
    }

    /**
     * @title 我的算力
     * @description 接口说明
     * @author cqd
     * @url /api/user/myComputingPower
     * @method POST
     *
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     * @return computing_power:算力
     * @return power_logs:算力记录@
     * @power_logs id:ID type:变动类型 time:时间 count:增减量
     *
     */
    public function myComputingPower(Request $request, Wallet $wallet, PowerLog $powerLog)
    {
        $user = $request->user;
        $computing_power = $wallet->get_user_power($user->id);

        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }

        if ($loadType == 'more') {
            $power_logs = $powerLog->filters([['user_id', '=', $user->id], ['id', '<', $startId]])->with('powertype')->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $power_logs = $powerLog->filters([['user_id', '=', $user->id], ['id', '>', $startId]])->with('powertype')->take($offset)->orderBy('id', 'desc')->get();
        }
        
        $power_logs = $power_logs->map(function ($power_log) {
            $power_log->type = $power_log->powertype->name;
            $power_log->time = substr($power_log->created_at, 0, 10);
            $lable = ($power_log->status == 1) ? '+' : '-';
            $power_log->count = $lable . $power_log->power;
            return $power_log->only(['id', 'type', 'time', 'count']);
        });
        return $this->success(compact('computing_power', 'power_logs'));
    }

    /**
     * @title 我的E格码
     * @description 接口说明
     * @author wjx
     * @url /api/user/myEMoney
     * @method POST
     *
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     * @return tmc:E格码
     * @return log:E格码记录@
     * @log id:ID comment:变动类型 created_at:变动时间 money:变动金额
     *
     */
    public function myEMoney(Request $request, EDealLog $DealLog, User $user)
    {
        $user = $request->user;
        $tmc = $user->wallet->tmc;
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }

        if ($loadType == 'more') {
            $log = $DealLog->filters([['user_id', '=', $user->id], ['id', '<', $startId]])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $log = $DealLog->filters([['user_id', '=', $user->id], ['id', '>', $startId]])->take($offset)->orderBy('id', 'desc')->get();
        }

        foreach ($log as $key => $value) {
            $log[$key] = $value->myEmoney();
        }

        return $this->success(compact('tmc', 'log'));

    }

    /**
     * @title 我的钱包
     * @description 接口说明
     * @author wjx
     * @url /api/user/myWallet
     * @method POST
     *
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     * @return money:余额
     * @return deposit:押金
     * @return log:钱包记录@
     * @log id:ID money:金额 type:充值途径 status:状态 created_at:时间
     *
     */
    public function myWallet(Request $request)
    {
        $user = $request->user;
        $data = [];
        $data['money'] = $user->wallet->money;
        $data['deposit'] = $user->wallet->deposit;
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }

        if ($loadType == 'more') {
            $recharge = Recharge::filters([['user_id', '=', $user->id], ['type', '=', 1], ['status', '=', 2], ['id', '<', $startId]])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $recharge = Recharge::filters([['user_id', '=', $user->id], ['type', '=', 1], ['status', '=', 2], ['id', '>', $startId]])->take($offset)->orderBy('id', 'desc')->get();
        }

        $data['log'] = $recharge->transform(function ($item) {
            $item->type = '微信充值';
            switch ($item->status) {
                case '1':
                    $item->status = '未付款';
                    break;
                case '2':
                    $item->status = '成功';
                    break;
                case '3':
                    $item->status = '未通过';
                    break;
                default:
                    break;
            }
            return [
                'id' => $item->id,
                'money' => '+' . $item->money,
                'type' => $item->type,
                'status' => $item->status,
                'created_at' => $item->created_at->toDateTimeString(),
            ];
        });

        return $this->success($data);
    }

    /**
     * @title 我的门店
     * @description 接口说明shop_type:店铺类型1线上2线下shop_role:1发起人2参与人 role:1店长2店员3模特
     * @author wjx
     * @url /api/user/myShop
     * @method POST
     *
     * @return pro_shop_lists:发起的店铺@
     * @pro_shop_lists shop_id:shop_id shop_role:1发起人 shop_type:店铺类型1线上2线下 address:地址 qrcode:二维码     * 
     * @return my_shop_lists:我参与的店铺列表@
     * @my_shop_lists shop_id:shop_id shop_role:2参与人 role:角色类型(array)1店长2店员3模特 shop_type:店铺类型1线上2线下 address:地址 qrcode:二维码
     */
    public function myShop(Request $request, User $user, Shop $shop, ShopRole $shopRole)
    {
        $user = $request->user;
        $user_id = $user->id;
        $pro_shop_lists = $shop::where(['user_id' => $user->id, 'status' => 3])->get();
        $pro_shop_lists->transform(function ($item) use ($user_id) {
            $item->shop_id = $item->id;
            $item->shop_role = 1;
            $item->qrcode = base64_encode(QrCode::format('png')->size(100)->generate(json_encode(['type' => 'memCard', 'shop_id' => $item->shop_id, 'user_id' => $user_id])));
            return $item->only(['shop_id', 'shop_role', 'shop_type', 'address', 'qrcode']);
        });

        $my_shop_lists = $shopRole::where(['user_id' => $user->id, 'status' => 1])->groupBy('shop_id')->get();

        $my_shop_lists->transform(function ($item) use ($user_id) {
            $item->shop_id = $item->shop_id;
            $item->shop_role = 2;
            $item->role = $this->get_user_role($user_id, $item->shop_id);
            $item->shop_type = $item->shop->shop_type;
            $item->address = $item->shop->address;
            $item->qrcode = base64_encode(QrCode::format('png')->size(100)->generate(json_encode(['type' => 'memCard', 'shop_id' => $item->shop_id, 'user_id' => $user_id])));
            return $item->only(['shop_id', 'shop_role', 'role', 'shop_type', 'address', 'qrcode']);
        });
        return $this->success(compact('pro_shop_lists', 'my_shop_lists'));
    }

    public function get_user_role($user_id, $shop_id)
    {
        $my_shop_lists = ShopRole::where(['user_id' => $user_id, 'status' => 1, 'shop_id' => $shop_id])->get();
        return $my_shop_lists->pluck('role');
    }
    /**
     * @title 我的交易记录
     * @description 接口说明
     * @author wjx
     * @url /api/user/my_deal_log
     * @method POST
     *
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     *
     * @return deal_logs:交易记录@
     * @deal_logs id:ID comment:变动类型 count:增减量 created_at:时间
     *
     */
    public function my_deal_log(Request $request, DealLog $dealLog)
    {
        $user = $request->user;
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if ($loadType == 'more') {
            $deal_logs = $dealLog->filters([['user_id', '=', $user->id], ['id', '<', $startId]])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $deal_logs = $dealLog->filters([['user_id', '=', $user->id], ['id', '>', $startId]])->take($offset)->orderBy('id', 'desc')->get();
        }

        $deal_logs = $deal_logs->map(function ($deal_log) {
            $label = ($deal_log->status == 1) ? '+' : '-';
            $deal_log->count = $label . $deal_log->money;
            return [
                'id' => $deal_log->id,
                'comment' => $deal_log->comment,
                'count' => $deal_log->count,
                'created_at' => $deal_log->created_at->toDateTimeString(),
            ];
        });
        return $this->success(compact('deal_logs'));
    }

    /**
     * @title 我的会员卡
     * @description 接口说明
     * @author wjx
     * @url /api/user/my_member_card
     * @method POST
     * @return date_range:有效期
     * @return member_type:卡类型
     *
     */
    public function my_member_card(Request $request)
    {
        $user = $request->user;
        if (!$user->is_member) {
            return $this->failed('你还不是会员');
        }
        $start = date('Y-m-d', $user->member_start_time);
        $end = date('Y-m-d', $user->member_end_time);
        $card_data = [];
        $card_data['date_range'] = $start . '至' . $end;

        switch ($user->member->time) {
            case '3':
                $card_data['member_type'] = $user->member->price . '/月  (' . $user->member->label . ')';
                break;
            case '6':
                $card_data['member_type'] = $user->member->price . '/年  (' . $user->member->label . ')';
                break;
            default:
                break;
        }
        return $this->success($card_data);
    }

    /**
     * @title 新手任务
     * @description 接口说明
     * @author cqd
     * @url /api/user/noviceTask
     * @method POST
     *
     * @return nickname:用户名
     * @return payment:支付管理
     * @return personal_signature:个性签名
     * @return count:算力奖励
     * @return power_level:算力级别
     */
    public function noviceTask(Request $request)
    {
        $user = $request->user;
        $data = [
            'nickname' => $user['nickname'] ? $user['nickname'] : '',
            'payment' => $user['weixin_openid'] ? '+10' : '',
            'personal_signature' => $user['personal_signature'] ? '+10' : '',
        ];

        $count = 0;
        $power_level = 0;
        foreach ($data as $key => $value) {
            $data['count'] = $value ? $count += 10 : $count + 0;
            $data['power_level'] = $value ? $power_level += 1 : $power_level + 0;
        }

        return $this->success($data);
    }
    /**
     * @title 我的店铺收益
     * @description 接口说明
     * @author wjx
     * @url /api/user/shop_profit
     * @method POST
     *
     * @param name:shop_id type:int require:1 default:1 other: desc:店铺ID
     * @param name:shop_role type:int require:1 default:1 other: desc:店铺类型(1我发起的2我参与的)
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     * 
     * @return profit:收益值
     * @return profit_log:收益记录@
     * @profit_log id:ID profit_name:变动类型 created_at:时间 money:收益金额
     */
    public function shop_profit(Request $request, Shop $shop)
    {
        $user = $request->user;
        $shop_id = $request->shop_id;
        $shop_role = $request->shop_role;
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if(!in_array($shop_role,[1,2])){
            return $this->failed('参数shop_role错误');
        }
        if (!$shop_id) {
            return $this->failed('缺少参数');
        }
        switch ($shop_role) {
            case '1':
                $profit = Shop::where([
                    ['id', $shop_id],
                    ['status', 3],
                ])->first();
                break;
            case '2':
                $profit = ShopRole::where([
                    ['shop_id', $shop_id],
                    ['status', 1],
                ])->first();
                break;
            default:
                break;
        }
        if ($profit) {
            $profit = $profit->shop_profit;
        }else{
            $profit = 0;
        }

        if ($loadType == 'more') {
            $profit_log = ShopProfit::filters([['id', '<', $startId],['user_id','=',$user->id], ['shop_id','=',$shop_id], ['shop_role','=',$shop_role]])->take($offset)->orderBy('id', 'desc')->get();
        } else {
            $profit_log = ShopProfit::filters([['id', '>', $startId],['user_id','=',$user->id], ['shop_id','=',$shop_id], ['shop_role','=',$shop_role]])->take($offset)->orderBy('id', 'desc')->get();
        }

        $profit_log->transform(function ($item) {
            $item->money = '+' . $item->money;
            return [
                'id' => $item->id,
                'profit_name' => $item->comment,
                'created_at' => $item->created_at->toDateString(),
                'money' => $item->money,
            ];
        });
        return $this->success(compact('profit','profit_log'));
    }
    
    /**
     * @title 我的收货地址
     * @description 接口说明 is_default:0否1是
     * @author wjx
     * @url /api/user/myAddrList
     * @method POST
     * @module 地址相关
     */
    public function myAddrList(Request $request)
    {
        $user = $request->user;
        $addr_list = UserAddr::where([['user_id', $user->id], ['is_deleted', 0]])->get();
        $addr_list->transform(function ($item) {
            $item->addr_id = $item->id;
            $item->full_address = $item->full_address;
            return $item->only(['id', 'username', 'phone', 'areaCode','full_address','detail', 'is_default']);
        });
        return $this->success($addr_list);
    }
    /**
     * @title 新增地址
     * @description 接口说明 is_default:0否1是
     * @author wjx
     * @url /api/user/addAddr
     * @method POST
     * @module 地址相关
     *
     * @param name:username type:string require:1 default: other: desc:收货人
     * @param name:phone type:string require:1 default: other: desc:收货电话
     * @param name:areaCode type:string require:1 default: other: desc:省市编号
     * @param name:province type:string require:1 default: other: desc:省
     * @param name:city type:string require:1 default: other: desc:市
     * @param name:street type:string require:1 default: other: desc:区/街道
     * @param name:detail type:string require:1 default: other: desc:详细地址
     * @param name:is_default type:int require:1 default: other: desc:是否默认
     */
    public function addAddr(Request $request, UserAddrRequest $addrRequest, UserAddr $user_addr)
    {
        $user = $request->user;
        $addrRequest['user_id'] = $user->id;
        if ($addrRequest->is_default == 1) {
            UserAddr::where(['user_id' => $user->id, 'is_default' => 1])->update(['is_default' => 0]);
        }

        $addr = $user_addr->fill($addrRequest->all());
        $addr->save();

        return $this->message('新增成功');
    }
    /**
     * @title 地址详情
     * @description 接口说明 is_default:0否1是
     * @author wjx
     * @url /api/user/addrDetail
     * @method POST
     * @module 地址相关
     * @param name:id type:int require:1 default: other: desc:地址id
     */
    public function addrDetail(Request $request, UserAddr $user_addr)
    {
        $user = $request->user;
        $user_addr = $user_addr->where('id', $request->id)->first();
        if(!$user_addr){
            return $this->failed('参数错误');
        }
        return $this->success($user_addr->only(['username', 'phone', 'areaCode','full_address','detail', 'is_default']));
    }
    /**
     * @title 修改地址
     * @description 接口说明 is_default:0否1是
     * @author wjx
     * @url /api/user/editAddr
     * @method POST
     * @module 地址相关
     *
     * @param name:id type:string require:1 default: other: desc:地址ID
     * @param name:username type:string require:1 default: other: desc:收货人
     * @param name:phone type:string require:1 default: other: desc:收货电话
     * @param name:province type:string require:1 default: other: desc:省
     * @param name:city type:string require:1 default: other: desc:市
     * @param name:street type:string require:1 default: other: desc:区/街道
     * @param name:detail type:string require:1 default: other: desc:详细地址
     * @param name:is_default type:int require:1 default: other: desc:是否默认
     */
    public function editAddr(Request $request, UserAddrRequest $addrRequest, UserAddr $user_addr)
    {
        $user = $request->user;
        $addrRequest['user_id'] = $user->id;
        if ($addrRequest->is_default == 1) {
            UserAddr::where(['user_id' => $user->id, 'is_default' => 1])->update(['is_default' => 0]);
        }

        $addr = $user_addr->where('id', $addrRequest->id)->first();

        $addr = $addr->fill($addrRequest->all());
        $addr->save();

        return $this->message('修改成功');
    }
    /**
     * @title 删除地址
     * @description 接口说明 is_default:0否1是
     * @author wjx
     * @url /api/user/delAddr
     * @method POST
     * @module 地址相关
     * @param name:id type:int require:1 default: other: desc:地址id     *
     */
    public function delAddr(Request $request, UserAddr $user_addr)
    {
        $user = $request->user;
        $addr = $user_addr->where('id', $request->id)->first();
        $addr->is_deleted = 1;
        if ($addr->save()) {
            return $this->message('删除成功');
        } else {
            return $this->failed('删除失败');
        }
    }
    /**
     * @title 设为默认地址
     * @description 接口说明
     * @author wjx
     * @url /api/user/setDefaultAddr
     * @method POST
     * @module 地址相关
     * @param name:id type:int require:1 default: other: desc:地址id
     */
    public function setDefaultAddr(Request $request, UserAddr $user_addr)
    {
        $user = $request->user;
        $request['user_id'] = $user->id;

        UserAddr::where(['user_id' => $user->id, 'is_default' => 1])->update(['is_default' => 0]);

        $addr = $user_addr->where('id', $request->id)->first();
        $addr->is_default = 1;
        $addr->save();
        return $this->message('操作成功');
    }

}
